﻿using System.IO;
using UnityEditor;
using XLua;

namespace GameCore
{
    [LuaCallCSharp]
    public class LuaBehaviourFormUiPanel : LuaBehaviour
    {
        public bool IsShowing { get; private set; }
        
        private LuaFunction luaOnInit;
        private LuaFunction luaOnShow;
        private LuaFunction luaOnHide;
        
        protected override void Awake()
        {
            base.Awake();
            
            LuaClass.Get("OnInit", out luaOnInit);
            LuaClass.Get("OnShow", out luaOnShow);
            LuaClass.Get("OnHide", out luaOnHide);
        }

        public void OnInit()
        {
            luaOnInit?.Call(LuaClass);
        }

        public void OnShow()
        {
            IsShowing = true;
            this.gameObject.SetActive(true);
            luaOnShow?.Call(LuaClass);
        }

        public void OnHide()
        {
            IsShowing = false;
            this.gameObject.SetActive(false);
            luaOnHide?.Call(LuaClass);
        }
        
        public override void Rebuild()
        {
#if UNITY_EDITOR
            string assetPath = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(gameObject);
            if (string.IsNullOrEmpty(assetPath)) return;
            if (File.Exists(assetPath))
            {
                File.Delete(assetPath);
            }
            if(File.Exists(assetPath + ".meta"))
            {
                File.Delete(assetPath + ".meta");
            }
            PrefabUtility.SaveAsPrefabAsset(gameObject, assetPath, out bool s);
#endif
        }
    }
}
